package com.ehotting.mqbd.zw.client.mq;

import com.ehotting.eaf.core.utils.SpringUtils;
import com.ehotting.eaf.core.utils.clazz.ClassScanHelper;
import com.ehotting.eaf.netty.action.Action;
import com.ehotting.mqbd.zw.api.domain.netty.ZwCommPacket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZwMqActionFactory implements InitializingBean {


    private final Logger logger = LoggerFactory.getLogger(ZwMqActionFactory.class);

    private final Map<String, ZwMqActionAble<ZwCommPacket>> messageActionMap = new HashMap<>();

    private String scanPackage;

    public ZwMqActionAble<ZwCommPacket> getAction(String action) {
        return messageActionMap.get(action);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void afterPropertiesSet() {
        logger.info("***************** Start scan package:"+scanPackage+" *****************");
        List<Class<?>> list = ClassScanHelper.getClassList(scanPackage, true , Action.class,null);

        for (Class<?> clazz : list) {
            Assert.notNull(ZwMqActionAble.class, "Type to check against must not be null");
            if (!ZwMqActionAble.class.isAssignableFrom(clazz)) {
                throw new RuntimeException(clazz.getSimpleName()	+ " is not assign ZwMqActionAble.");
            }
            Action actionType = clazz.getAnnotation(Action.class);
            if (actionType != null) {
                logger.info("Add class:{},key:{}",clazz,actionType.value());
                ZwMqActionAble<ZwCommPacket> action = (ZwMqActionAble<ZwCommPacket>) SpringUtils.getBean(clazz);
                Assert.isTrue(!messageActionMap.containsKey(actionType.value()),
                        "messageActionMap["+actionType.value()+"] has contains "+messageActionMap.get(actionType.value())+".");
                messageActionMap.put(actionType.value(), action);
            }
        }
        logger.info("*********************** Finish scan package."+"*************************");
    }


    public void setScanPackage(String scanPackage) {
        this.scanPackage = scanPackage;
    }

}
